<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template>
  <div class="execution">
    <basic-container>
      <el-row :gutter="20" style="margin-left:5px;margin-top: 5px">
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-select v-model="searchForm.dbCode" placeholder="请选择数据源" @change="getList(page)">
              <el-option v-for="item in dataSourceList" :key="item.id" :label="item.title" :value="item.name" />
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <avue-input v-model="searchForm.tableName" placeholder="表名称" ></avue-input>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-button type="primary" icon="el-icon-search" @click="getList(page)">搜索</el-button>
            <el-button type="primary" icon="el-icon-document" @click="downDocument">导出表结构文档</el-button>
<!--            <el-button type="primary" icon="el-icon-download" @click="openBatchGen">批量生成</el-button>-->
          </div>
        </el-col>
      </el-row>
      <avue-crud
              v-model="form"
              v-model:page="page"
              :permission="getPermission"
              v-bind="bindVal"
              v-on="onEvent"
              :option="option"
              :data="tableData"
      >


        <template #menu="scope">
          <el-button link type="primary"  icon="el-icon-view" @click="handleTableColumn(scope.row, scope.index)">字段</el-button>
          <el-button link type="primary"  icon="el-icon-edit" @click="openSearch(scope.row, scope.index)" title="与查询配置公用">配置</el-button>
          <el-button link type="primary"  icon="el-icon-check" @click="openGen(scope.row, scope.index)">生成</el-button>

        </template>
      </avue-crud>

      <el-dialog  v-if="tableGenVisible"  v-model="tableGenVisible" title="生成配置" width="80%" lock-scroll>
        <div class="pull-auto">
          <avue-form ref="rowData" :option="tableGenOption" v-model="rowData">

            <template #menu-form="{ size }">
<!--              <el-button type="primary"-->
<!--                         :size="size"-->
<!--                         @click="handleSaveItem">保存</el-button>-->
              <el-button type="primary"
                         :size="size"
                         @click="handleGen()">生成</el-button>
              <el-button :size="size"
                         @click="resetForm">清空</el-button>
            </template>
          </avue-form>
        </div>
      </el-dialog>


      <el-dialog  v-if="tableSearchVisible"  v-model="tableSearchVisible" title="查询配置" width="94%" lock-scroll>
        <div class="pull-auto">

          <avue-form :option="qoption"
                     v-model="qform"   @submit="handleQSubmit"> </avue-form>

<!--            <avue-crud-->
<!--                    ref="itemCrud"-->
<!--                    v-model:page="itemPage"-->
<!--                    :data="tableItemData"-->
<!--                    :option="tableItemOption"-->
<!--                    @row-update="handleItemUpdate"-->
<!--            />-->


        </div>
      </el-dialog>


    </basic-container>
    <!--表字段-->
    <el-dialog title="字段预览" v-if="tableColumnVisible" v-model="tableColumnVisible" width="80%" top="5vh" append-to-body><tableColumn :queryData="rowData" v-if="tableColumnVisible" /></el-dialog>
    <!-- 预览界面 -->
    <el-dialog title="代码预览"  v-if="previewVisible" v-model="previewVisible" width="80%" top="5vh" append-to-body><Preview :queryData="rowData" v-if="previewVisible" /></el-dialog>

  </div>
</template>

<script>
import {fetchGenPage, handleGenCode} from "@/framework-admin/api/code/generator";
import {tableOption, tableGenOption} from "./generator";
import tableColumn from "./tableColumn.vue";
import Preview from "./preview.vue";
import {pageCore,listCore,delCore,getCore,saveCore} from "@/framework-core/api/core/api";
import curdMixin from '@/framework-core/mixins/crud';
import website  from '@/framework-core/config/website';
import store from '@/framework-core/store/';

import {fqmtableOption} from "./formQueryModel";
import pinyin from 'js-pinyin'

export default {
  name: "CodeGenerator",
  mixins: [curdMixin],
  components: {Preview, tableColumn},
  data() {
    return {
      //搜索
      pageConfig:{"url":"/sys/table","permissionConfig":"sys_table"},
      dataSourceList: [],
      searchForm: {
        dsName:undefined,
        tableName:undefined
      },

      //表格
      tableLoading: false,
      tableData: [],
      option: tableOption,
      qoption:{
        column: [
          {
            label: '应用名称',
            prop: 'title',
            "rules": [{
              required: true,
              message: '应用名称不能为空',
              trigger: 'blur'
            }],
            control: (val, form) => {

              if(!val){
                return
              }
              // if(form.app){
              //   return
              // }
              form.app = pinyin.getCamelChars(val);
              return;
              // return {
              //   app: {
              //     value: pinyin.getCamelChars(val)
              //   }
              // }

            }
          },
          {
            label: '应用编码',
            prop: 'app',
            "rules": [{
              required: true,
              message: '应用编码不能为空',
              trigger: 'blur'
            }],
          }
        ]
      },
      qform:{},
      //字段显示
      tableItemData:[],
      tableColumnVisible: false,
      tableGenVisible: false,
      tableSearchVisible:false,
        tableGenOption: tableGenOption,
        tableItemOption: fqmtableOption,
      previewVisible:false,
      rowData: {
        dsName: undefined,
        tableName : undefined
      },

    };
  },
  created() {
    this.getDataSourceList();
  },
  methods: {

    getDataSourceList() {
      listCore("sys/datasource", {}).then(response => {
        if (response.data.data && response.data.data.data.length > 0) {
          this.dataSourceList = response.data.data.data;
          this.searchForm.dbCode = this.dataSourceList[0].name;

          if (this.dataSourceList.length > 0) {
            tableOption.column[0].dicData = [];
            this.dataSourceList.forEach(function(element) {
              tableOption.column[0].dicData.push({"label":element.title,"value":element.name})
            });
          } else {
            //  this.$message.error("数据源信息列表为空,请添加数据源");
          }

        } else {
          this.$message.error("数据源信息列表为空,请添加数据源");
        }
      });
    },

    getList(page, params,sorts) {
      this.tableLoading = true;
      return fetchGenPage(
        this.buildParam(page, params,sorts)
      ).then(response => {
        this.tableData = response.data.data.records;
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    refreshChange() {
      this.getList(this.page);
    },

    //表的列信息
    handleTableColumn: function(row) {
      this.tableColumnVisible = true;
      this.rowData.dbName	 = row.dbName;
      // this.rowData.tableComment = this.searchForm.tableComment;
      this.rowData.tableName = row.tableName;


    },
    openSearch: function(row) {

      this.getDictItemList(row.dbName, row.tableName);
    },

    handleView: function() {
      this.previewVisible = true;
    },

    //生成代码
    handleGen() {
      handleGenCode(this.rowData).then((response) => {
        this.tableGenVisible = false;
        this.downFile(response.data.data.url,response.data.data.tag);
        this.$message.success("代码导出成功");
      });
    },

    handleSaveItem(){

    },
    openGen: function(row) {
      this.tableGenVisible = true;
      this.rowData.dbName	 = row.dbName;
      this.rowData.tableComment = row.tableComment;
      this.rowData.tableName = row.tableName;

    },

    // openBatchGen() {
    //   if (this.$refs.crud.tableSelect.length <= 1 || this.$refs.crud.tableSelect.length > 10) {
    //     this.$message.error("选中表数量不合法，数量最少2个或最多为10个");
    //     return false;
    //   }
    //   let tableName = [];
    //   for (const table of this.$refs.crud.tableSelect) {
    //     tableName.push(table.tableName);
    //   }
    //   this.tableGenVisible = true;
    //   this.rowData.tableName = tableName.join("-");
    // },

    downDocument() {
      let tableNames = [];
      for (const table of this.$refs.crud.tableSelect) {
        tableNames.push(table.tableName);
      }
      //let queryParams = {dbCode: this.searchForm.dbCode, tableNames: tableNames.join() };

      this.downFile(website.baseUrl+"/api/sys/generator/doc?dbCode="+this.searchForm.dbCode+"&tableNames="+tableNames.join()+"&jrtoken="+store.getters.token, this.searchForm.dbCode + ".doc");
    },

    //======字典项表格相关=====tableItemData
    getDictItemList(db,table) {
      this.tableSearchVisible = true;
      this.qform.db = db;
      this.qform.tableName = table;



      // this.tableItemData = [];
      // queryApp({"db":db,"table":table}
      //       ).then(response => {
      //
      //   this.tableItemData = response.data.data.data;
      // });
    },

    handleQSubmit (form, done) {
      saveCore("/form/queryApp",form).then(() => {
        this.$message.success("成功");
        this.tableSearchVisible =false
        if(done){
          done();
        }
      });
    },

    handleItemUpdate (form, index, done, loading) {

      this.$message.success( JSON.stringify(form))
      done()
    },
    beforeClose: function (done, type) {
      done();
    }


  }
};
</script>

<style lang="scss" scoped></style>
